<template>
	<view class="container">
		<view class="buttons">
			<view class="button phoneBtn" v-if="!isConfirm && (!isCancel) && (!isConfirmApply) && disturbstatus!=1"
				@click="handleCall">
				<view>
					<image src="http://images.linglinggong.net/images/main/call.png" mode="aspectFill"></image>
					<text>拨打电话</text>
				</view>
				<view>
					<text class="cancel-time" style="width: 50rpx; text-align: center;">虚拟号生成中...</text>
				</view>
			</view>
			<view class="button phoneBtn" v-if="isConfirm && (!isCancel) && (!isConfirmApply)" @click="handleConfirm">
				<text>确认接单</text>
			</view>
			<view class="button OldStaff" v-if="(!isCancel) && (!isConfirmApply) && (OldStaff) && disturbstatus!=1"
				@click="handleConfirm">
				<text>直接接单</text>
				<view class="">
					<text class="cancel-time" style="width: 50rpx; text-align: center;">老雇员专享</text>
				</view>
			</view>
			<view class="button OldStaff" v-if="(!isCancel) && (!isConfirmApply) && disturbstatus==1"
				@click="handleConfirm">
				<text>直接接单</text>
				<view class="">
					<text class="cancel-time" style="width: 50rpx; text-align: center;">免打扰接单</text>
				</view>
			</view>
			<view class="button quxiaobaoming" @click="handleCancelAlert()" v-if="!isCancel && (!isConfirmApply)">
				<text>取消报名</text>
				<view>
					<text class="cancel-time"
						style="width: 50rpx;display: inline-block;text-align: center;">{{countTimeM }}</text>
					<text>:</text>
					<text class="cancel-time"
						style="width: 50rpx;display: inline-block;text-align: center;">{{countTimeS}}</text>
					<text>:</text>
					<text class="cancel-time"
						style="width: 50rpx;display: inline-block;text-align: center;">{{countTimeMS}}</text>
				</view>
			</view>
			<view class="button" v-if="isCancel">
				<text>已取消报名</text>
			</view>
		</view>
		<view class="address" @click="handleMap(1)">
			<view>
				<image src="http://images.linglinggong.net/icon1/14.png" mode="aspectFill"></image>
				<text>{{ ShowAddres }}</text>
			</view>
			<text>(点击进入导航)</text>
		</view>
		<view class="tip">
			<image class="tipText-image" src="http://images.linglinggong.net/icon3/rtygughcjgkjhvgjhkh.png"
				mode="aspectFill"></image><text class="tipText-new">注：确认接单后，<text
					class="tipText-new-Focus">请按任务时间前往工作地点。</text></text>
			<!-- <text>注：确认接单后，</text><text class="tipText">请按任务要求时间前往工作地点</text><text>。如需拨号通话，</text><text class="tipText">请勿在通话记录内回拨</text>。 -->
		</view>
		<modal :isShowModal="isShowModal" :modalStytle="modalStytle" @handleLeft="handleLeft" @handleRight="handleRight"
			:titleContect="titleContect" :middleContext="middleContext" :leftContext="leftContext"
			:rightContext="rightContext"></modal>
		<warningPromptBanner :listId="1" style="position: fixed; bottom: 68rpx;"></warningPromptBanner>
	</view>
</template>
<script>
	import Voice from '@/libs/QS-baiduyy.js'
	import {
		isToDay
	} from '../../libs/unit.js'
	import warningPromptBanner from '@/components/warningPromptBanner/warningPromptBanner'
	export default {
		data() {
			return {
				isShowModal: false,
				modalStytle: 3,
				titleContect: '提示', //弹框标题
				middleContext: '是否拨打电话', //弹框中间的内容
				leftContext: '取消', //弹框按钮左边的内容
				rightContext: '确认', //弹框按钮右边的内容
				isConfirm: false, //是否打过电话
				isCancel: false, //是否已取消订单
				taskUserId: '', //雇主id
				orderId: '', //订单id
				orderCreateTime: '', //订单创建时间
				taskId: '', //任务id
				orderDetail: {}, //订单详情
				taskDetail: {}, //任务详情
				bossPhone: '', //雇主电话
				overtime_cancel: '', //自动取消订单时间
				countTime: '', //倒计时
				countTimeM: '', //分
				countTimeS: '', //秒
				countTimeMS: '', //毫秒
				timer: null, //定时器
				voiceTimer: null, // 语音播报定时器
				street: {}, //街道
				imgPath: '', //图片路径
				isConfirmApply: false, //是否已经报名
				flagOpen: true, //防止重复点击
				virtualPhoneNumber: '', //虚拟电话号码
				OldStaff: false, //是否老雇员
				ShowAddres: "", //展示地址
				disturbstatus: 0,
				receivedTaskStartTime: 0,
				quxiaoFlag: 1,
				quxiaoClick: false,
			}
		},
		components: {
			warningPromptBanner,
		},
		methods: {
			getShowAdd(add) {
				add = add.split('·')
				add.pop()
				return add.join('·')
			},
			// 打给雇主
			handleCall() {
				if (this.taskDetail == {} || this.orderId == "") {
					setTimeout(() => {
						this.handleCall()
					}, 2000)
				} else {
					let phone = this.taskDetail.phonenumber ? this.taskDetail.phonenumber : this.taskDetail.telephone
					this.phone_bind_middle_number(phone, false, this.orderId).then(res => {
						this.isShowModal = true
						if (res) {
							this.middleContext = '*虚拟号已生成，仅支持本次通话*'
						} else {
							this.middleContext = '是否拨打电话' + phone
						}
					})
				}
			},
			//弹框左键
			handleLeft() {
				this.isShowModal = false
			},
			//弹框右键
			handleRight() {
				this.isShowModal = false
				if (this.quxiaoClick) {
					this.quxiaoFlag++
					uni.setStorageSync('quxiaoFlag', [uni.getStorageSync('date'), this.quxiaoFlag])
					this.handleCancel()
					return
				}
				let phone = this.taskDetail.phonenumber ? this.taskDetail.phonenumber : this.taskDetail.telephone
				this.phone_bind_middle_number(phone, true, this.orderId)
				this.isConfirm = true
				this.cache_task_dialed_mobile()
				// 打电话了
				uni.setStorageSync('hasUnconfirm', 2)
				/* this.phone_bind_middle_number(this.taskDetail.telephone) */
			},
			//获取虚拟电话
			async phone_bind_middle_number(telephone, isCall, id) {
				let res = await this.$fetch(this.$api.phone_bind_middle_number, {
					phone: telephone,
					orderId: id
				}, 'POST', 'form')
				console.log('获取虚拟电话res~~~~~~', res)
				if (res.code) {
					if (!isCall) {
						//this.middleContext = '是否拨打电话' + telephone
						return false
					} else {
						uni.makePhoneCall({
							phoneNumber: telephone
						})
					}
				}
				if (!isCall) {
					if (res.code == '500') {
						//this.middleContext = '是否拨打电话' + telephone
						return false
					} else if (res.data.overTime == '1000') {
						//this.middleContext = '是否拨打电话' + telephone
						return false
					}
					//this.middleContext = '此号码是平台虚拟电话，请不要重复拨打！'
					if (res.data.middleNumber && res.data.overTime != '1000') {
						//this.middleContext = '此号码是平台虚拟电话，请不要重复拨打！'
						return true
					}
					return
				}
				if (res.data.middleNumber && res.data.overTime != '1000') {
					uni.makePhoneCall({
						phoneNumber: res.data.middleNumber
					})
				} else {
					uni.makePhoneCall({
						phoneNumber: telephone
					})
					// uni.showToast({
					// 	title: '对方号码忙线中，请稍后重试！',
					// 	icon: 'none'
					// })
				}
			},
			// 缓存是打过电话
			async cache_task_dialed_mobile() {
				console.log('上传打过电话this.taskId', this.taskId, this.orderId)
				let res = await this.$fetch(this.$api.cache_task_dialed_mobile, {
					taskId: this.taskId
				}, 'POST')
				console.log('上传打过电话', res)
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				this.isConfirm = true
			},
			// 查询是否打过电话
			async get_task_mobile_cache() {
				// console.log('查询是否打过电话this.taskId',this.taskId,this.orderId)
				let res = await this.$fetch(this.$api.get_task_mobile_cache, {
					taskId: this.taskId
				}, 'POST')
				// console.log('查询是否打过电话~~~~~~~~',res)
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				this.isConfirm = res.msg == 1 ? true : false
				// 报名了，取消了 0
				if (this.isConfirmApply || this.isCancel) {
					uni.setStorageSync('hasUnconfirm', 0)
					console.log('获取接单语音提醒状态~~~~~接单成功页面——查询是否打过电话有取消或确认', uni.getStorageSync('hasUnconfirm'))
					// 打过电话
				} else if (this.isConfirm && uni.getStorageSync('checked1')) {
					uni.setStorageSync('hasUnconfirm', 2)
					Voice('请确认接单或取消订单')
				} else if (!this.isConfirm && uni.getStorageSync('checked1')) {
					uni.setStorageSync('hasUnconfirm', 1)
					if (this.OldStaff && this.disturbstatus != 1) {
						uni.setStorageSync('OldStaff', true)
						Voice('这是老雇主的任务，可以直接接单哦。')
					} else if (this.disturbstatus == 1) {
						Voice('这是开启免打扰的任务，请直接接单哦')
					} else {
						uni.removeStorageSync('OldStaff')
						Voice('请尽快拨打电话与雇主确认订单')
					}
				}
			},
			handleCancelAlert() {
				this.isShowModal = true
				this.modalStytle = 3
				this.titleContect = '取消订单'
				this.middleContext = this.quxiaoFlag == 1 ? '订单取消后无法重复报名，确认取消吗？' : this.quxiaoFlag == 2 ?
					'订单取消次数将达上限，确认取消吗？' : '订单取消次数已达上限，确认取消吗？'
				this.leftContext = '取消'
				this.rightContext = '确认'
				this.quxiaoClick = true
			},
			// 取消报名
			async handleCancel() {
				if (!this.flagOpen) return
				this.flagOpen = false
				setTimeout(() => {
					this.flagOpen = true
				}, 1000)
				let res = await this.$fetch(this.$api.apply_check, {
					orderId: this.orderId,
					checkStatus: 0
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				uni.setStorageSync('hasUnconfirm', 0)
				uni.showToast({
					title: '订单已取消，请查看其它工作',
					icon: 'none'
				})
				setTimeout(() => {
					// uni.switchTab({
					// 	url: '/pages/index/index'
					// })
					uni.navigateTo({
						url: '/pages/cancellationOrder/cancellationOrder?orderId=' + this.orderId
					})
				}, 800)
				uni.setStorageSync('shuaxin', true)
				console.log('获取接单语音提醒状态~~~~~接单成功页面取消', uni.getStorageSync('hasUnconfirm'))
			},
			// 判断是否为老雇员
			async isOldStaff() {
				let res = await this.$fetch(this.$api.task_order_employer, {
					taskId: this.taskId,
					token: uni.getStorageSync('token')
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				if (res.data >= 2) {
					this.OldStaff = true
				}
			},
			// 确认接单
			async handleConfirm() {
				Voice('您已接单，请按约定时间前往工作地点')
				console.log('确认接单', this.orderId)
				let res = await this.$fetch(this.$api.apply_check, {
					orderId: this.orderId,
					checkStatus: 2
				}, 'POST')
				console.log('确认接单', res)
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				uni.setStorageSync('hasUnconfirm', 0)
				console.log('获取接单语音提醒状态~~~~~接单成功页面接单', uni.getStorageSync('hasUnconfirm'))
				uni.showToast({
					title: '接单成功~',
					icon: 'none'
				})
				uni.$emit('openDaikgong', {})
				uni.setStorageSync('receivedTaskStartTime', this.receivedTaskStartTime)
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order-detail/order-detail?id=' + this.orderId
					})
				}, 600)
			},
			//获取订单详情
			async order_list(taskId) {
				let res = await this.$fetch(this.$api.order_by_taskId, {
					taskId: taskId
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				// console.log('获取订单详情~~~~~~~~~~~~~~~任务id', taskId, res)
				this.orderId = res.data.id
				this.orderCreateTime = res.data.createTime
				this.isCancel = res.data.status == 0 ? true : false
				this.isConfirmApply = res.data.status > 1 ? true : false
				this.countDown(res.data.createTime)
				this.order_detail(this.orderId)
				// this.get_task_mobile_cache() //是否打过电话
				this.receivedTaskStartTime = res.data.taskStartTime
			},
			// 倒计时计算
			countDown(orderCreateTime) {
				this.overtime_cancel = uni.getStorageSync('overtime_cancel')
				console.log('过期时间', this.overtime_cancel, '订单时间', orderCreateTime)
				if (this.isConfirmApply || this.isCancel) return // 如果确认或者取消过就不倒计时了
				orderCreateTime = orderCreateTime.replace(/-/g, '/')
				orderCreateTime = new Date(orderCreateTime).getTime() + this.overtime_cancel * 60 * 1000
				orderCreateTime = new Date(orderCreateTime)
				let year = orderCreateTime.getFullYear();
				let month = orderCreateTime.getMonth() + 1;
				let day = orderCreateTime.getDate();
				let hours = orderCreateTime.getHours();
				let minute = orderCreateTime.getMinutes();
				let second = orderCreateTime.getSeconds();
				//我们来定义一个未来时间 用它来进行倒计时。
				let time = new Date().getTime() //当前时间
				let future = new Date(year, month, day, hours, minute, second).getTime(); //未来时间
				let p = (future - time) / 1000; //时间差
				//时分秒转换公式
				let m = Math.floor(p % 86400 % 3600 / 60) < 10 ? '0' + Math.floor(p % 86400 % 3600 / 60) : Math.floor(p %
					86400 % 3600 / 60)
				let s = Math.floor(p % 60) < 10 ? '0' + Math.floor(p % 60) : Math.floor(p % 60)
				let ms = Math.floor((p * 1000) % 1000) < 10 ? '0' + Math.floor(p * 1000 % 1000) : Math.floor(p * 1000 %
					1000)
				this.countTime = m + ":" + s + ":" + ms;
				this.countTimeM = m
				this.countTimeS = s
				this.countTimeMS = ms
				this.timer = setInterval(() => {
					let time = new Date; //当前时间
					let future = new Date(year, month, day, hours, minute, second); //未来时间
					let p = (future - time) / 1000; //时间差
					//时分秒转换公式
					let m = Math.floor(p % 86400 % 3600 / 60) < 10 ? '0' + Math.floor(p % 86400 % 3600 / 60) : Math
						.floor(p % 86400 % 3600 / 60)
					let s = Math.floor(p % 60) < 10 ? '0' + Math.floor(p % 60) : Math.floor(p % 60)
					let ms = Math.floor((p * 1000) % 1000) < 10 ? '0' + Math.floor(p * 1000 % 1000) : String(Math
						.floor(p * 1000 % 1000)).slice(0, 2)
					this.countTime = m + ":" + s + ":" + ms
					this.countTimeM = m
					this.countTimeS = s
					this.countTimeMS = ms
					// console.log('倒计时中~~~~~',uni.getStorageSync('hasUnconfirm'))
					if (this.isCancel || this.isConfirmApply) {
						clearInterval(this.timer)
						console.log('由于其他原因倒计时结束~~~~~是否取消', this.isCancel, '是否确认报名', this.isConfirmApply, '是否打电话',
							this.isConfirm, this.timer)
						uni.setStorageSync('hasUnconfirm', 0)
						console.log('获取接单语音提醒状态~~~~~接单成功页面——查询是否打过电话有取消或确认', uni.getStorageSync('hasUnconfirm'))
						return
					}
					if (m == 0 && s == 0) {
						// 查询接单，取消状态
						this.$fetch(this.$api.order_by_taskId, {
							taskId: this.taskId
						}, 'POST').then(res => {
							this.isCancel = res.data.status == 0 ? true : false
							this.isConfirmApply = res.data.status > 1 ? true : false
						})
						uni.setStorageSync('hasUnconfirm', 0)
						console.log('获取接单语音提醒状态~~~~~接单成功页面倒计时结束', uni.getStorageSync('hasUnconfirm'))
						clearInterval(this.timer)
						// this.timer = null
						console.log('倒计时结束~~~~~~~~~~~~~~~~~~~~~~', this.timer)
						this.handleCancel()
						this.isCancel = true
						return
					}
				}, 99)
			},
			// 获取任务详情
			async task_detail(taskId) {
				let res = await this.$fetch(this.$api.task_detail, {
					taskId: taskId
				}, 'POST')
				this.taskDetail = res.data
				this.ShowAddres = this.getShowAdd(this.taskDetail.address)
				this.disturbstatus = res.data.disturbstatus
			},
			// 获取订单详情
			async order_detail(orderId) {
				let res = await this.$fetch(this.$api.order_detail, {
					orderId: orderId
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				// 整理数据,res.data.user为null，则改为""
				Object.getOwnPropertyNames(res.data).forEach(function(key) {
					res.data[key] = res.data[key] == null ? '' : res.data[key]
				})
				this.orderDetail = res.data
				console.log('this.orderDetail', this.orderDetail)
			},
			// 配置数据
			async getData() {
				let res = await this.$fetch(this.$api.property_list_by_type, {
					type: 1
				}, 'POST')
				if (res.code) return uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				//接单超时取消 单位 分钟 整数
				this.overtime_cancel = res.data.overtime_cancel
				uni.setStorageSync('overtime_cancel', res.data.overtime_cancel)
				this.order_list(this.taskId) //获取订单，开始计时
			},
			//打开地图
			handleMap(flag) {
				// 确认报名去地图，不能回来
				if (flag == 2) {
					this.isConfirmApply = true
					uni.redirectTo({
						url: '/pages/map-job/map-job?lat=' + this.taskDetail.lat + '&lng=' + this.taskDetail.lng +
							'&address=' + this.taskDetail.address + '&name=' + this.taskDetail.name,
					})
				} else {
					uni.navigateTo({
						url: '/pages/map-job/map-job?lat=' + this.taskDetail.lat + '&lng=' + this.taskDetail.lng +
							'&address=' + this.taskDetail.address + '&name=' + this.taskDetail.name,
					})
				}
			},
			getReceived() {
				let item = [this.taskId, this.isConfirm, this.OldStaff]
				let list = uni.getStorageSync('ReceivedInfo') ? uni.getStorageSync('ReceivedInfo') : []
				list.push(item)
				uni.setStorageSync('ReceivedInfo', list)
			},
		},
		onLoad(options) {
			this.taskId = options.taskId
			this.isOldStaff()
			// 清除定时器
			clearInterval(this.timer)
			this.timer = null
			console.log('开始~~~~~~~~~~~~~~~~~~~~~~~~~~~onLoad', this.timer)
			this.getData() //
			this.task_detail(options.taskId) //获取任务详情
			if (uni.getStorageSync('quxiaoFlag')) {
				this.quxiaoFlag = isToDay(uni.getStorageSync('quxiaoFlag')[0]) ? uni.getStorageSync('quxiaoFlag')[1] : 1
			}
		},
		onShow() {
			if (this.isConfirmApply) {
				uni.redirectTo({
					url: '/pages/order-detail/order-detail?id=' + this.orderId
				})
			} else if (this.isCancel) {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
			this.get_task_mobile_cache()
		},
		onUnload() {
			this.getReceived()
			clearInterval(this.timer)
			this.timer = null
			console.log('结束onUnload清除定时器~~~~~~~~~~~~~~', this.timer)
			// 
		},
	}
</script>
<style lang="less" scoped>
	page {
		background-color: #FFFFFF;
	}

	.container {
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100vh;

		// justify-content: center;
		// 按钮
		&>.buttons {
			margin-top: 90rpx;
			font-size: 22px;

			&>.button {
				width: 600rpx;
				height: 150rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 74rpx;
				margin-bottom: 76rpx;

				&:active {
					opacity: 0.7;
				}
			}

			.OldStaff {
				flex-direction: column;
				background: #FFC30C;
				border-radius: 74rpx;
				box-shadow: 0 2px 6px 0 rgba(255, 247, 0, 0.4);
			}

			.cancel-time {
				font-size: 17px;
			}

			.phoneBtn {
				color: #FFFFFF;
				background: #4E9800;
				box-shadow: 0 2px 6px 0 rgba(78, 152, 0, 0.40);
				margin-bottom: 80rpx;
				flex-direction: column;

				&>view:nth-child(1) {
					display: flex;
					justify-content: center;
					align-items: center;

					&>image {
						width: 42rpx;
						height: 42rpx;
						margin-right: 20rpx;
					}
				}
			}

			.quxiaobaoming {
				flex-direction: column;
				background: #F39B19;
				box-shadow: 0 2px 6px 0 rgba(255, 110, 0, 0.40);
			}
		}

		&>.address {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 100rpx;
			width: 600rpx;
			font-size: 24rpx;

			// border-style: dashed;
			&>view {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				&>image {
					width: 24rpx;
					height: 26rpx;
					margin-right: 10rpx;
				}
			}

			&>text {
				color: rgba(64, 33, 16, 0.50);
			}
		}

		&>.tip {
			width: 600rpx;
			color: #E02020;

			// line-height: ;
			&>.tipText {
				font-weight: bold;
			}
		}
	}

	.tipText-new {
		font-size: 32rpx;
		font-weight: 500;
		color: #D6110F;
		line-height: 48rpx;
	}

	.tipText-new-Focus {
		font-size: 32rpx;
		font-weight: 500;
		color: #D6110F;
		line-height: 48rpx;
		font-weight: bold;
	}

	.tipText-image {
		width: 30rpx;
		height: 30rpx;
		margin-right: 16rpx;
	}
</style>